/*
   Copyright 2010 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.coders;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import org.latestbit.smartobjects.ISerializableObject;
import org.latestbit.smartobjects.encrypters.IDataEncrypter;
import org.latestbit.smartobjects.exceptions.SmartBusSystemException;
import org.latestbit.smartobjects.io.ResizableByteBuffer;

public class StdDataTypesCoderGrammar implements ISerializableObject {

	protected Map<String, Integer> grammarMapByStr = new HashMap<String, Integer>();
	protected Map<Integer, String> grammarMapById = new HashMap<Integer, String>();
	
	@Override
	public void serialize(IDataTypesCoder coder, IDataEncrypter encrypter, ResizableByteBuffer writeBuffer) throws SmartBusSystemException {
		coder.encodeObjectMap(grammarMapByStr.size(), writeBuffer);
		for(Map.Entry<String, Integer> entry: grammarMapByStr.entrySet()) {
			coder.encodeString(entry.getKey(), writeBuffer);
			coder.encodeUInt32(entry.getValue(), writeBuffer);
		}
	}

	@Override
	public void deserialize(IDataTypesCoder coder, IDataEncrypter encrypter, ByteBuffer readBuffer) throws SmartBusSystemException {
		int size = coder.decodeObjectMap(readBuffer);
		for(int i=0; i<size; i++) {
			String str = coder.decodeString(readBuffer);
			int id = coder.decodeUInt32(readBuffer);
			grammarMapById.put(id, str);
			grammarMapByStr.put(str, id);
		}
	}

	@Override
	public String getObjectType() {
		return "StdDataTypesCoderGrammar";
	}

	public int registerGrammarElement(String namedObject) {
		Integer result = grammarMapByStr.get(namedObject);
		if(result == null) {
			result = grammarMapByStr.size() + 1;
			grammarMapByStr.put(namedObject, result);
			grammarMapById.put(result, namedObject);
		}
		return result;
	}

	public String findGrammarElement(int id) {		
		return grammarMapById.get(id);
	}

	public void reset() {
		grammarMapByStr.clear();
		grammarMapById.clear();
	}

}
